package cn.tedu.knows.faq.controller;

import cn.tedu.knows.commons.exception.ServiceException;
import cn.tedu.knows.commons.model.Comment;
import cn.tedu.knows.faq.service.ICommentService;
import cn.tedu.knows.faq.vo.CommentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tedu.cn
 * @since 2021-10-27
 */
@RestController
@RequestMapping("/v2/comments")
@Slf4j
public class CommentController {

    @Autowired
    private ICommentService commentService;

    // @PostMapping后面不写("") 也是可以的
    @PostMapping
    public Comment postComment(
            @Validated CommentVo commentVo,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user){
        log.debug("接收到表单信息:{}", commentVo);
        if(result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        // 调用业务逻辑层
        Comment comment=commentService
                .saveComment(commentVo,user.getUsername());
        // 返回↓↓↓↓↓↓↓↓新增的评论对象
        return comment;

    }
    // localhost:8080/v1/comments/23/delete

    // 删除评论的控制器方法
    @GetMapping("/{id}/delete")
    public String removeComment(
            @PathVariable Integer id,
            @AuthenticationPrincipal UserDetails user){
        boolean isDelete=commentService
                .removeComment(id,user.getUsername());
        if(isDelete){
            return "ok";
        }else {
            return "fail";
        }

    }

    @PostMapping("/{id}/update")
    public Comment updateComment(
            @PathVariable Integer id,
            @Validated CommentVo commentVo,
            BindingResult result,
            @AuthenticationPrincipal UserDetails user){
        log.debug("修改表单信息:{}",commentVo);
        log.debug("要修改的评id:{}",id);
        if(result.hasErrors()){
            String msg=result.getFieldError().getDefaultMessage();
            throw new ServiceException(msg);
        }
        // 业务逻辑层调用
        Comment comment=commentService.updateComment(
                id,commentVo,user.getUsername());
        // 千万别忘了return comment
        return comment;

    }


}









